var express = require('express');
var router = express.Router();
const axios = require('axios');
const iconv = require('iconv-lite');
const cheerio = require('cheerio');
const { geRecentDate } = require('../serve/oil');

/* GET home page. */
router.get('/get', async function (req, res, next) {
    const response = await axios.get('https://oil.nbsasu.com/', { responseType: 'arraybuffer' });
    let decodedStr = iconv.decode(new Buffer.from(response.data), 'UTF-8');
    const $ = cheerio.load(decodedStr);
    const cpbaojiaElement = $('.table-container>.layui-table');
    const table = cpbaojiaElement.find('tbody');
    let data = [];
    table.find('tr').each((i, row) => {
        // if (i !== 0) {
            const area = $(row).find('td').eq(0).text(); // 或者 'th' 如果是表头的话
            const oilPrice92 = $(row).find('td').eq(1).text(); // 或者 'th' 如果是表头的话
            const oilPrice95 = $(row).find('td').eq(2).text(); // 或者 'th' 如果是表头的话
            const oilPrice98 = $(row).find('td').eq(3).text(); // 或者 'th' 如果是表头的话
            const oilPrice0 = $(row).find('td').eq(4).text(); // 或者 'th' 如果是表头的话
            const updateTime = $(row).find('td').eq(5).text(); // 或者 'th' 如果是表头的话

            data.push({
                area,
                oilPrice92,
                oilPrice95,
                oilPrice98,
                oilPrice0,
                updateTime
            })
        // }

    });
    res.send({
        code: 1,
        data,
        msg: '获取成功'
    })
});

router.get('/geRecentDate', async function (req, res, next) {
    try {
        const data = await geRecentDate();
        res.send(data);
    } catch (err) {
        console.error(err);
        return {
            code: -1,
            msg: 'err:' + err
        }
    }
});

module.exports = router;